//
//  UserManager.m
//  MiPaiTest
//
//  Created by TonyGenius on 15/11/29.
//  Copyright (c) 2015年 GSH. All rights reserved.
//

#import "UserManager.h"

@implementation UserManager

+(id)defaultManager
{
    //创建单例
    static UserManager *userManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        userManager = [[self alloc] init];
    });
    return userManager;
}

//获取本地access_token
- (NSString *) isAccessTokenUnuse;
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *access_token = [userDefaults objectForKey:@"access_token"];
    NSLog(@"access_token____%@",access_token);
    
    return access_token;
}

//检查access_token是否失效或不存在
- (BOOL)accessTokenIsInvalidate
{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *access_token = [userDefault objectForKey:@"access_token"];
    
    if (access_token == nil || access_token.length == 0) {
        NSLog(@"access_token为空");
        return YES;
    }
    
    NSDate *expireDate = [userDefault objectForKey:@"exprise_in"];
    if ([expireDate timeIntervalSinceNow] < 0) {
        NSLog(@"失效 access_token");
        return YES;
    }
    NSLog(@"access_token____%@",access_token);
    return NO;
}

//将access_token存在本地
- (void)saveAccessTokenInBox:(NSDictionary *)sender
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *access_token = [userDefaults objectForKey:@"access_token"];
    if (access_token != nil || access_token.length != 0) {
        [userDefaults removeObjectForKey:@"access_token"];
    }
    
    [userDefaults setObject:sender[@"access_token"] forKey:@"access_token"];
    [userDefaults setObject:sender[@"user_id"] forKey:@"user_id"];
    NSNumber *expriseInNum = sender[@"expire_time"];
    NSDate *nowDate = [NSDate date];
    NSDate *date = [nowDate dateByAddingTimeInterval:[expriseInNum doubleValue]];
    [userDefaults setObject:date forKey:@"expire_time"];
    
    //强行写入
    [userDefaults synchronize];
}

@end
